// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Configuration.cs" company="ecblog.codeplex.com">
//   emrecoskun.net - ibrahimatay.com
// </copyright>
// <summary>
//   Defines the Configuration type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace EcBlog.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    using System.Linq;

    using EcBlog.Data;
    using EcBlog.Data.Sql;
    using EcBlog.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<EcModelContext>
    {
        public Configuration()
        {
#if DEBUG
            this.AutomaticMigrationsEnabled = true;
            this.AutomaticMigrationDataLossAllowed = false; 
#else
            AutomaticMigrationsEnabled = false;
            AutomaticMigrationDataLossAllowed = false; 
#endif
        }

        public static void ComplateSetup(EcUnitOfWork unitOfWork)
        {
            AddDefaultSettings(unitOfWork);
            AddDefaultLayout(unitOfWork);
            AddDefaultTags(unitOfWork);
            AddDefaultPages(unitOfWork);
        } 

        public static bool HasSetupCompleted()
        {
            bool hasSetupCompleted;
            try
            {
                using (var context = new EcModelContext())
                {
                    context.Database.Initialize(true);
                    var setting = context.SiteSettings.FirstOrDefault(c => c.SettingKey == "SetupCompleted");
                    hasSetupCompleted = bool.Parse(setting != null ? setting.SettingValue : bool.FalseString);
                }
            }
            catch (Exception)
            {
                hasSetupCompleted = false;
            }

            return hasSetupCompleted;
        }

        public static void Preinstall(IEcUnitOfWork unitOfWork)
        {
            AddDefaultSettings(unitOfWork);
        }

        public static string GetSiteDefault(SiteSettingKey key)
        {
            return GetSiteDefault(Enum.GetName(typeof(SiteSettingKey), key));
        }

        public static string GetSiteDefault(string name)
        {
            switch (name)
            {
                case "SiteTitle":   // 1
                    return "Enter your site title";
                case "SiteSlogan":  // 2
                    return "Enter your site slogan";
                case "SiteUrl":     // 3 
                    return "http://yoursite.com";
                case "AdminAuthenticationId":   // 4
                    return "admin";
                case "Email": // 5
                    return "Enter your site mail adress";
                case "EmailHost": // 6
                    return "Enter your site mail host adress";
                case "EmailPort": // 7
                    return "Enter your site mail host port";
                case "EmailUserName": // 8
                    return "Enter your site mail user name";
                case "EmailUserPassword": // 9
                    return "Enter your site mail password";
                case "DateFormat": // 10
                    return "dd/MM/yyyy";
                case "TimeFormat": // 11
                    return "HH:mm";
                case "NumberOfVisiblePageInWeb": // 12
                    return "5";
                case "NumberOfVisiblePageInRss": // 13
                    return "10";
                case "CommentAlertMailMessage":     // 14
                    return "A new comment has been added";
                case "CommentAlertMailSubject":     // 15
                    return "A new comment has been added";
                case "CommentAlertEMail":           // 16
                    return "Enter your comment alert mail adress";
                case "SiteDescription":         // 17
                    return "Enter your site description";
                case "Author":                  // 18
                    return "Enter your author name";
                case "Copyright":   // 19
                    return "Copyright (c) 2011 www.yoursite.com";
                case "RssUrl":  // 20
                    return "Enter your rss url";
                case "GoogleSiteVerificationKey":   // 21
                    return string.Empty;
                case "BingSiteVerificationCode":   // 22
                    return string.Empty;
                case "YahooSiteVerificationCode":   // 23
                    return string.Empty;
                case "GoogleAnalyticsCode":   // 24
                    return string.Empty;
                case "FacebookLink":   // 25
                    return string.Empty;
                case "TwitterUserName":   // 26
                    return string.Empty;
                case "RssLink":   // 27
                    return string.Empty;
                case "UseHttpInSlugAddress":        // 28
                    return "false";
                case "UrlSuffix":       // 29
                    return string.Empty;
                case "DefaultLayoutName":       // 30
                    return "Default Layout";
                case "SendAlertMailOnNewComment":       // 31
                    return "false";
                case "EmailEnableSsl":      // 32
                    return "false";
                case "FeedLanguage":        // 33
                    return "en-GL";
                case "SlugUrlFormat":       // 34
                    return "{year}/{month}/{slug}";
                case "BlogRpcId":           // 35
                    return string.Empty;
                case "UseSocialiconsInExtra": // 36
                    return "true";
                case "SetupCompleted":
                    return "false";
                case "Culture":
                    return "en-GL";
                case "ContactMessage":
                    return "Contact for me";
                default: return string.Empty;
            }
        }

        protected override void Seed(EcModelContext context)
        {
            base.Seed(context);
            var unitOfWork = new EcUnitOfWork(context); 
            ComplateSetup(unitOfWork);
        }

        private static void AddDefaultSettings(IEcUnitOfWork unitOfWork)
        {
            // if (unitOfWork.SiteSettingRepository.Get().Any()) return;
            foreach (var name in Enum.GetNames(typeof(SiteSettingKey)))
            {
                var settingExists = unitOfWork.SiteSettingRepository.Get().Any(c => c.SettingKey == name);
                if (!settingExists)
                {
                    unitOfWork.SiteSettingRepository.Create(
                        new SiteSetting { SettingKey = name, SettingValue = GetSiteDefault(name) });
                }

                unitOfWork.Save();
            }
        }

        private static void AddDefaultLayout(IEcUnitOfWork unitOfWork)
        {
            var defaultLayoutName = unitOfWork.SiteSettingRepository[SiteSettingKey.DefaultLayoutName];
            if (unitOfWork.LayoutRepository.Get().Any(c => c.Name.Equals(defaultLayoutName)))
            {
                return;
            }

            unitOfWork.LayoutRepository.Create(
                new Layout
                { 
                    LayoutPath = @"~/Content/themes/default/views/_Layout.cshtml",
                    Name = "Default Layout"
                });
            unitOfWork.Save();
        }

        private static void AddDefaultTags(IEcUnitOfWork unitOfWork)
        {
            if (unitOfWork.PageRepository.Get().Any() || unitOfWork.TagRepository.Get().Any())
            {
                return;
            }

            unitOfWork.TagRepository.Create(
                new Tag
                {
                    TagName = "bloging",
                    TagSlug = "bloging"
                });
            unitOfWork.TagRepository.Create(
                new Tag
                {
                    TagName = "next step",
                    TagSlug = "next-step"
                });
            unitOfWork.Save();
        }

        private static void AddDefaultPages(IEcUnitOfWork unitOfWork)
        {
            if (unitOfWork.PageRepository.Get().Any())
            {
                return;
            }

            unitOfWork.PageRepository.Create(
                new Page
                {
                    Title = "Wellcome ecBlog",
                    Slug = "wellcome-ec-blog",
                    ContentHtml =
                        "<p>Now your&nbsp;instalation is completed. </p><h1>Wellcome ecBlog</h1><p>ecBlog is a easy blog platform. Just run and use it.</p><h2>with <a href=\"http://ecblog.codeplex.com/documentation\" target=\"_blank\">ecBlog</a></h2><p>You can send post with html editor,&nbsp;&nbsp;create custom pages for custom urls and change every things in run time.&nbsp; You'll manage your site on <a href=\"../admin\">admin panel</a>. </p><p></p>",
                    LayoutId = 1,
                    IsCommentable = true,
                    IsPublish = true,
                    LastModified = DateTime.Now,
                    Published = DateTime.Now,
                    Created = DateTime.Now,
                    ShowPostList = true,
                    Summary = "wellcome ecBlog",
                    Tags = unitOfWork.TagRepository.Get().ToList()
                });
            unitOfWork.PageRepository.Create(
                new Page
                {
                    Title = "Custom Page",
                    Slug = "/custom-page",
                    ContentHtml =
                        @"<p>This is a custom page.</p>",
                    LayoutId = 1,
                    IsCommentable = true,
                    IsPublish = true,
                    LastModified = DateTime.Now,
                    Published = DateTime.Now,
                    Created = DateTime.Now,
                    ShowPostList = false,
                    Summary = "custom page",
                    Tags = new[] { unitOfWork.TagRepository.Get().First() }
                });
            unitOfWork.PageRepository.Create(
                new Page
                {
                    Title = "Tags",
                    Slug = "/archive",
                    ContentHtml =
                        "<script type=\"text/javascript\">$(function() { $('#tagList').load('/widget/taglist'); });</script><div class=\"widget\" id=\"tagList\"></div>",
                    LayoutId = 1,
                    IsCommentable = false,
                    IsPublish = true,
                    LastModified = DateTime.Now,
                    Published = DateTime.Now,
                    Created = DateTime.Now,
                    ShowPostList = false,
                    Summary = "tags"
                });
            unitOfWork.PageRepository.Create(
                new Page
                {
                    Title = "Archive",
                    Slug = "/date-archive",
                    ContentHtml =
                        "<script type=\"text/javascript\">$(function() { $('#tagList').load('/widget/taglistbydate'); });</script><div class=\"widget\" id=\"tagList\"></div>",
                    LayoutId = 1,
                    IsCommentable = false,
                    IsPublish = true,
                    LastModified = DateTime.Now,
                    Published = DateTime.Now,
                    Created = DateTime.Now,
                    ShowPostList = false,
                    Summary = "date archive"
                });
            unitOfWork.PageRepository.Create(
                new Page
                {
                    Title = "Contact",
                    Slug = "/contact",
                    ContentHtml =
                        "<script type=\"text/javascript\">$(function() { $('#contact').load('/blog/contact'); });</script><div class=\"widget\" id=\"contact\"></div>",
                    LayoutId = 1,
                    IsCommentable = false,
                    IsPublish = true,
                    LastModified = DateTime.Now,
                    Published = DateTime.Now,
                    Created = DateTime.Now,
                    ShowPostList = false,
                    Summary = "contact"
                });
            unitOfWork.Save();
        }
    }
}
